package com.qf.fmall.utils;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;

import java.util.*;

public class WxPayUtils {

    public static final String APPID = "wx632c8f211f8122c6";
    public static final String MCH_ID = "1497984412";
    public static final String APPKEY = "sbNCm1JnevqI36LrEaxFwcaT0hkGxFnC";

    // 统一下单接口 url
    public static final String WX_UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    // 查询订单状态的接口的url
    public static final String WX_QUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery";


    public static String getOrderStatus(String orderId){

        //1. 调用微信的查询订单状态接口，获取订单的状态
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("appid",APPID);
        hashMap.put("mch_id",MCH_ID);
        hashMap.put("nonce_str", UUID.randomUUID().toString().replaceAll("-",""));
        hashMap.put("out_trade_no",orderId);
        // 计算签名
        String sign = createSign(hashMap);
        hashMap.put("sign",sign);

        String xml = XmlUtil.mapToXmlStr(hashMap);
        //2. 发送请求
        String resultXML = HttpRequest.post(WX_QUERY_URL)
                .body(xml)
                .execute()
                .body();

        System.out.println(resultXML);

        //3. 解析响应的xml数据
        Map<String, Object> map = XmlUtil.xmlToMap(resultXML);
        String result
                = (String) map.get("trade_state");
        System.out.println(result);
        return result;
    }



    /**
     * 向微信支付平台的统一下单接口发送请求，获取可以用来生成二维码的支付url
     * @return
     */
    public static String getPayUrl(String content,String orderId,Integer totalFee){

        //1. 处理请求体中的参数
        // 必传参数的接口文档地址如下
        // https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("appid",APPID);
        hashMap.put("mch_id",MCH_ID);
        hashMap.put("nonce_str", UUID.randomUUID().toString().replaceAll("-",""));
        hashMap.put("body",content);
        hashMap.put("out_trade_no",orderId);
        hashMap.put("total_fee",1);  // 订单的金额，单位是分
        hashMap.put("notify_url","http://47.118.45.73:8080/pay/callback");
        hashMap.put("trade_type","NATIVE");

        // 计算签名
        String sign = createSign(hashMap);
        hashMap.put("sign",sign);

        // 将 hashMap 转换为XML 字符串
        String xmlData = XmlUtil.mapToXmlStr(hashMap);
        //2. 发送http请求给微信支付接口
        String resultXML =
                HttpRequest.post(WX_UNIFIEDORDER_URL) // 发送pos请求
                .body(xmlData)  // 设置post请求体中的数据
                .execute() // 将请求发送出去
                .body();   // 获取响应体中的数据
//        System.out.println(resultXML);

        //3. 解析响应的XML数据
        Map<String, Object> resultMap = XmlUtil.xmlToMap(resultXML);
        String url = (String) resultMap.get("code_url");

        return url;
    }


    private static String createSign(HashMap<String, Object> hashMap) {
        
        //1. 获取所有参数的名字 ，进行排序 
        Set<String> keySet = hashMap.keySet();
        String[] keyArr = new String[keySet.size()];
        keySet.toArray(keyArr);

        Arrays.sort(keyArr); // 把key按照 ascii 进行升序排序
        
        //2. 拼串 StringA 
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < keyArr.length; i++) {
            String key = keyArr[i];
            Object value = hashMap.get(key);
            stringBuffer.append(key);
            stringBuffer.append("=");
            stringBuffer.append(value);
            stringBuffer.append("&");
        }
        String stringA = stringBuffer.toString();
        
        //3. 拼接自己的商户的密钥
        String stringSignTemp = stringA + "key=" + APPKEY;

        //4. 进行MD5运算
        String sign = DigestUtil.md5Hex(stringSignTemp).toUpperCase();

        return sign;
    }

    public static void main(String[] args) {
//        String payUrl = getPayUrl("测试商品", "2024011813370001", 1);
//        System.out.println(payUrl);

        System.out.println(getOrderStatus("2024011813370001"));
    }

}
